﻿using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using ST.Buz.Base;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Common.Data;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Office;
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;
using System.IO;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using System.Reflection;

namespace ST.Buz.Service
{
	/// <summary>
	/// 只针对当前项目的扩展接口定义
	/// </summary>
	public partial interface IServiceSysSiteConfig
	{
		SiteConfig GetSiteConfig(UserSession sessionCurrent);

		SiteConfig GetSiteConfig();
	}

	/// <summary>
	/// 只针对当前项目的扩展接口实现
	/// </summary>
	public partial class ServiceSysSiteConfig : IServiceSysSiteConfig
	{
		private readonly BuzContext context;
		private readonly ILogger logger;
		private readonly IMemoryCache cache;
		private readonly IOptions<SiteConfig> opt;
		public readonly string CACHE_KEY = "SITE";
		public ServiceSysSiteConfig(BuzContext ctx,
			IMemoryCache _cache,
			IOptions<SiteConfig> _opt,
			ILogger<ServiceSysSiteConfig> log)
		{
			cache = _cache;
			opt = _opt;

			context = ctx;
			logger = log;
		}

		public SiteConfig GetSiteConfig(UserSession sessionCurrent)
		{
			SiteConfig siteConfig = null;
			try
			{
				siteConfig = cache.Get(CACHE_KEY) as SiteConfig;
				if (siteConfig == null && opt != null && opt.Value != null)
				{
					siteConfig = opt.Value;
					siteConfig.AppVersion = Assembly.GetEntryAssembly().GetName().Version.ToString(3);
#if DEBUG
					siteConfig.AppVersion += " beta";
#endif
					var dbVersion = context.ExecuteScalar("SELECT TOP 1 MigrationId FROM [__EFMigrationsHistory] ORDER BY [MigrationId] DESC", null, CommandType.Text);
					if (dbVersion != null && dbVersion != DBNull.Value)
					{
						var version = Convert.ToString(dbVersion);
						var splits = version.Split('_');
						siteConfig.DBVersion = splits.Length > 1 ? splits[1] : version;
					}
					cache.Set(CACHE_KEY, siteConfig);
				}
			}
			catch (Exception ex)
			{
				//throw ex;
				logger.LogError(ex, ex.Message);
			}
			return siteConfig;
		}

		public SiteConfig GetSiteConfig()
		{
			return GetSiteConfig(null);
		}
	}
}